package com.shz.controller;


import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.shz.controller.helper.HelperController;
import com.shz.dto.AliPay;
import com.shz.pojo.MenuOrders;
import com.shz.pojo.Orders;
import com.shz.pojo.Trip;
import com.shz.service.MenuOrdersService;
import com.shz.service.OrdersService;
import com.shz.service.TripService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Api(tags = "用户支付模块")
@RestController
@RequestMapping("/alipay2")
public class AliPayController2 {
    @Resource
    MenuOrdersService menuOrdersService;

    private static final ConcurrentHashMap<Long, MenuOrders> orderMap = new ConcurrentHashMap<>();


    public static void addOrder(MenuOrders o) {

        orderMap.put(o.getId(),o);
    }

    public static MenuOrders getHaveOrder(Long id) {
        return orderMap.get(id);
    }
    public static void deleteHaveOrder(Long id) {
        orderMap.remove(id);
    }

    /**
     * 支付
     *
     * @param aliPay 阿里支付
     * @return {@link String}
     */
    @ApiOperation(value = "支付链接")
    @GetMapping("/pay")
    public String pay(AliPay aliPay) throws IOException {
        AlipayTradePagePayResponse response;
        try {
            //  发起API调用（以创建当面付收款二维码为例）
            response = Factory.Payment.Page()
                    .pay(aliPay.getSubject(), aliPay.getTraceNo(), aliPay.getTotalAmount(), "http://127.0.0.1:5501/views/user_order.html");
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        System.out.println(response.getBody());
        return response.getBody();
    }

    /**
     * 付款通知
     *
     * @param request 请求
     * @return {@link String}
     * @throws Exception 异常
     */
    // 设置失效时间阈值（比如5分钟）
    private static final long EXPIRATION_THRESHOLD_MINUTES = 1;
    private final Map<Long, Object> locks = new ConcurrentHashMap<>();
    @Resource
    TripService tripService;
    @ApiOperation(value = "支付回调")
    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }
            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String aliPaytradeNo = params.get("trade_no");
            System.out.println(tradeNo + ":" + gmtPayment + ":" + aliPaytradeNo);
            System.out.println(params);
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                List<Long> removeList = new ArrayList<>();
                long l = Long.parseLong(tradeNo);
                MenuOrders orders = orderMap.get(l);
                menuOrdersService.save(orders);
                menuOrdersService.update(new UpdateWrapper<MenuOrders>().eq("id", tradeNo)
                        .set("gmtPayment", gmtPayment).set("aliPaytradeNo", aliPaytradeNo)
                );
//                tripService.update(new UpdateWrapper<Trip>().eq("id",orders.getTid()).setSql("countNum=countNum"+orders.getCount()));

                orderMap.remove(l);
                HelperController.remove(orders.getUid());


            }
        }
        return "success";
    }

}
